package com.example.netchat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class NetchatDatabase extends SQLiteOpenHelper {
	private static final String DB_NAME = "com.example.netchat";
	private Context mContext;

	public NetchatDatabase(Context context) {
		super(context, DB_NAME, null, 1);

		setContext(context);
	}

	private void setContext(Context context) {
		this.mContext = context;
	}

	private Context getContext() {
		return this.mContext;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		runScript(db, "create_db.sql");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int old_version, int new_version) {
	}

	private void runScript(SQLiteDatabase db, String scriptName) {
		try {
			InputStream inputStream = getContext().getAssets().open(scriptName);
			InputStreamReader reader = new InputStreamReader(inputStream);
			BufferedReader bufferedReader = new BufferedReader(reader);

			String line = null;
			while ((line = bufferedReader.readLine()) != null
					&& line.trim().length() > 0) {
				db.execSQL(line);
			}
			try {
			} finally {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
				if (reader != null) {
					reader.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
